package myShoppingCart

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/models/Admin"
	USER "OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

type PostMyShoppingCart struct {
	beego.Controller
}

func (c *PostMyShoppingCart) PostMyShoppingCart() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/myShoppingCart/PostMyShoppingCart"
	var err error

	shoppingCart := &USER.ShoppingCart{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()

	productId := c.GetString("product")
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	fmt.Println(openid, productId)
	shoppingCart.User = &USER.WXUser{OpenId: openid}
	shoppingCart.Product = &Admin.ProductDetailed{ProductId: productId}
	sql := "select * from `shopping_cart` where `user_id`=? and `product_id`=?"
	err = o.Raw(sql, openid, productId).QueryRow(&shoppingCart)
	fmt.Println(err, shoppingCart)
	if err != nil && err.Error() == "<QuerySeter> no row found" {
		s := strconv.FormatInt(time.Now().Unix(), 10)
		shoppingCart.ShoppingCartId = "SCI" + s
		shoppingCart.Num = 1
		_, err = o.Insert(shoppingCart)
		shoppingCart.Num = 1
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}

	} else if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	} else {
		sql = "update `shopping_cart` set `num`=`num`+1 where `user_id`=? and `product_id`=?"
		sqlExec, err := o.Raw(sql, openid, productId).Exec()
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		num, err := sqlExec.RowsAffected()
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		} else if num == 0 {
			c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("num==0"), addr, "num==0")
			return
		}
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
